const express = require("express");
//引入连接池模块
const pool = require("../pool.js");

//创建路由器对象
const r = express.Router();

//添加路由

//查询摄影师详情页
r.get('/detail',(req,res,next)=>{
  console.log(req.query);
  let obj=req.query;
  let sql='select * from photo_detail where pid = ?';
  pool.query(sql,[obj.pid],(err,result)=>{
    if(err){
      next(err);
      return;
    };
    if(result.length!=0){
      res.send({code:200,msg:'查询成功',data:result[0]});
      console.log(result[0]);
    }
  });
});
r.get('/video',(req,res,next)=>{
  
  let sql='select * from video';
  pool.query(sql,(err,result)=>{
	  console.log(result);
    if(err){
      next(err);
      return;
    };
    if(result.length!=0){
      res.send({code:200,msg:'查询成功',data:result});
      console.log(result);
    }
  });
});
  
//用户注册接口
r.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(id) AS count FROM xzqa_author WHERE username=?';
  pool.query(sql, [username], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'INSERT xzqa_author(username,password) VALUES(?,MD5(?))';
      pool.query(sql, [username, password], (error, results) => {
        if (error) throw error;
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
    }
  });
});

// 用户登录接口
r.post('/login', (req, res) => {
  //获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  // SQL语句
  let sql = 'SELECT id,username,nickname,avatar FROM xzqa_author WHERE username=? AND password=MD5(?)';
  pool.query(sql, [username, password], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //登录失败
      res.send({message:'login failed',code:201});
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:results[0]});
    }
  });

});


//导出路由器对象
module.exports=r;